<?php

namespace app\index\controller;

use think\Validate;
use app\index\model\Account as AccountModel;
use app\index\model\Group as GroupModel;

class Account extends Base
{
    public function _initialize()
    {
        parent::_initialize();
    }

    public function save()
    {
        $validate = new Validate([
            'name' => 'require|max:16',
            'group_id' => 'require',
            'wechat_id' => 'require',
        ]);
        $data = input('post.');
        if (! $validate->check($data)) {
            $this->error($validate->getError());
            return ;
        }

        $data = input('post.');
        $fileupload = $this->upload('qrcode');
        if ($fileupload['result'] == 0) {
            $this->error($fileupload['error']);
            return ;
        }
        $data['qr_img'] = $fileupload['file'];

        $account = new AccountModel($data);
        $account->allowField(true)->save();

        $this->success('成功');
    }

    public function edit($id)
    {
        $account = AccountModel::find($id);
        $groups  = GroupModel::all();

        return view('edit', compact('account', 'groups'));
    }

    public function update()
    {
        $data = input('post.');
        $account = new AccountModel;
        if (request()->file('qrcode')) {
            $fileupload = $this->upload('qrcode');
            if ($fileupload['result'] == 0) {
                $this->error($fileupload['error']);
                return ;
            }
            $data['qr_img'] = $fileupload['file'];
        }
        $account->save($data, ['id' => $data['id']]);

        $this->success('修改成功', 'index/admin');
    }

    public function delete($id)
    {
        // TODO: 认证
        AccountModel::destroy($id);

        $this->success('成功');
    }

    public function status($id, $status)
    {
        // TODO: 认证
        $account = AccountModel::get($id);
        $account->status = $status;
        $account->save();

        $this->success('成功', 'index/admin');
    }

    public function fans()
    {
        $data = input('get.');
        $account = AccountModel::get($data['id']);
        $account->fans = $data['fans'];
        $account->save();

        $this->success();
    }

    private function upload($filename)
    {
        if (! request()->file($filename)) {
            return array('result' => 0, 'error' => '请上传图片');
        }
        $file = request()->file($filename);
        $path = 'public/uploads/qrcode/';
        $info = $file->validate(['ext' => 'jpg,jpeg,png'])->move(ROOT_PATH . $path);
        if($info){
            return array('result' => 1, 'file' => $path . $info->getSaveName());
        }else{
            return array('result' => 0, 'error' => $file->getError());
        }
    }
}
